package com.itheima.riggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.riggie.common.CustomException;
import com.itheima.riggie.domain.Category;
import com.itheima.riggie.domain.Dish;
import com.itheima.riggie.domain.Setmeal;
import com.itheima.riggie.mapper.CategoryMapper;

import com.itheima.riggie.service.CategoryService;
import com.itheima.riggie.service.DishService;
import com.itheima.riggie.service.EmployeeService;
import com.itheima.riggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    @Override
    public void remove(Long id) {
        //添加查询条件,根据分类id进行查询菜品数据
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper=new LambdaQueryWrapper<>();
        //去查询dish这张表, 是否有这个 外键等于这个要删除的id,如果有,则不能直接删除此id
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        //调用继承mp接口的service中的count,去统计 查询出来的个数
        int count1 = dishService.count(dishLambdaQueryWrapper);
        //如果大于一个,就代表这个id,关联了外键
        //如果出现关联,抛出一个业务异常
        if (count1>0){
            throw new CustomException("当前分类下关联了菜品,不能删除");
        }
        //查询当前分类是否关联了套餐,如果管理,不能删除
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper=new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if (count2>0){
            throw new CustomException("当前分类下关联了套餐,不能删除");
        }

        //正常删除
        super.removeById(id);

    }
}
